import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/entity/other/resource_entity.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';

class ResourceDialogImageWidget extends StatelessWidget {
  const ResourceDialogImageWidget(
      {super.key,
      required this.tip,
      required this.image,
      required this.width,
      required this.height});

  final ResourceEntity tip;
  final Image image;
  final double width;
  final double height;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: width,
            height: height,
            decoration: BoxDecoration(
                image:
                    DecorationImage(image: image.image, fit: BoxFit.fitWidth)),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                SizedBox(
                  height: tip.dialogConfig?.btnTop ?? 0,
                ),
                QkdButton(
                  onPressed: () {
                    var jump = tip.href;
                    if (jump?.contains(Routes.viewpoint) ?? false) {
                      Utils.onEvent('tc', params: {'tc': '方案'});
                    } else if (jump?.contains(Routes.userPage) ?? false) {
                      Utils.onEvent('tc', params: {'tc': '专家'});
                    } else {
                      Utils.onEvent('tc');
                    }
                    Get.back(result: true);
                  },
                  height: tip.dialogConfig?.btnHeight ?? height,
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          OutlinedButton(
              onPressed: () {
                Get.back();
              },
              style: OutlinedButton.styleFrom(side: BorderSide.none),
              child: SizedBox(
                width: 32,
                height: 32,
                child: Image.asset(Utils.getImgPath("close_icon_circle.png")),
              ))
        ],
      ),
    );
  }
}

class ResourceDialogUtil {
  static List<String> showedLbts = SpUtils.lbtDialogIds;

  static bool checking = false;

  static Future<bool> _handleResourceDialog(
      ResourceEntity element, String route) async {
    // final splited = element.title?.split(":") ?? [];
    // if (splited.length == 2 && route != splited[1]) { return false; }
    if (element.dialogConfig?.route != route) {
      return false;
    }

    final id = element.id ?? 0;
    final idx = showedLbts.indexWhere((element) => element.startsWith("$id:"));
    final str = idx >= 0 ? showedLbts[idx] : "$id:0";
    final time =
        DateTime.fromMillisecondsSinceEpoch(int.parse(str.split(":").last));
    final now = DateTime.now();

    if (idx >= 0) {
      final seconds = element.dialogConfig?.duration;
      if (seconds == null || seconds > now.difference(time).inSeconds) {
        return false;
      }
    }

    Widget? dialogWidget;

    log("check lbt dialog ${element.toJson()}");
    bool r = false;
    if (element.imgUrl?.isNotEmpty ?? false) {
      log("check lbt dialog img ${element.toJson()}");
      try {
        final f =
            await DefaultCacheManager().getSingleFile(element.imgUrl!.trim());
        final bytes = await f.readAsBytes();
        final image = await decodeImageFromList(bytes);
        final w = Get.width * 0.75;
        dialogWidget = ResourceDialogImageWidget(
            tip: element,
            image: Image.memory(bytes, scale: 3),
            width: w,
            height: (w / image.width) * image.height);
      } catch (e) {
        log("$e");
      }
    } else if (element.dialogConfig?.content?.isNotEmpty ?? false) {
      log("check lbt dialog content ${element.toJson()}");
      dialogWidget = QkdDialog.alert(element.dialogConfig?.content ?? '');
    }

    if (dialogWidget != null && Get.overlayContext != null) {
      r = true;
      final msg = "$id:${DateTime.now().millisecondsSinceEpoch}";
      if (idx >= 0) {
        showedLbts[idx] = msg;
      } else {
        showedLbts.add(msg);
      }
      log("check $showedLbts");

      final a = await showDialog(
          barrierDismissible: false,
          context: Get.overlayContext!,
          builder: (context) => dialogWidget!);
      if (a is bool && a) {
        await element.doJump();
      }
    }
    return r;
  }

  static checkShowDialog({String? curRoute}) async {
    if (checking) {
      return;
    }
    if (Get.isDialogOpen ?? true) {
      return;
    }

    final route = curRoute ?? Get.currentRoute;
    if (route == Routes.navigation || route == '/') {
      return;
    }

    checking = true;
    await Future.delayed(500.ms);

    bool handleSomething = false;
    List<ResourceEntity> list = [];
    List<ResourceEntity> dialogList = Get.find<ResourceService>().dialog;
    list.addAll(dialogList);
    if (User.isLogin) {
      list.addAll(Get.find<ResourceService>().loginDialog);
    }

    for (var element in list) {
      try {
        if (await _handleResourceDialog(element, route)) {
          handleSomething = true;
        }
      } catch (err) {}
    }

    if (handleSomething) {
      //控制 只有40个 lbt 对象
      if (showedLbts.length > 40) {
        showedLbts.removeRange(0, showedLbts.length - 40);
      }
      SpUtils.lbtDialogIds = showedLbts;
    }

    checking = false;
  }
}
